<template>
  <div class="history-viewer">
    <!-- 搜索栏 -->
    <div class="search-bar mb-4">
      <div class="flex items-center gap-3">
        <Input
          v-model="searchKeyword"
          placeholder="搜索历史记录..."
          class="flex-1"
          @input="handleSearch"
        />
        <!-- <Button
          variant="outline"
          @click="clearSearch"
          :disabled="!searchKeyword"
        >
          清除
        </Button>
        <Button @click="refreshHistory" :disabled="isLoading">
          <svg
            v-if="isLoading"
            class="w-4 h-4 mr-2 animate-spin"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
            />
          </svg>
          <svg
            v-else
            class="w-4 h-4 mr-2"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
            />
          </svg>
          刷新
        </Button> -->
      </div>
    </div>

    <!-- 错误提示 -->
    <div
      v-if="error"
      class="error-message mb-4 p-3 bg-red-50 border border-red-200 rounded-lg"
    >
      <div class="flex items-center gap-2 text-red-700">
        <svg
          class="w-4 h-4"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
          />
        </svg>
        {{ error }}
        <Button variant="ghost" size="sm" @click="clearError" class="ml-auto">
          <svg
            class="w-4 h-4"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </Button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats mb-4">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="stat-card bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div class="text-2xl font-bold text-blue-700">{{ totalRecords }}</div>
          <div class="text-sm text-blue-600">总记录数</div>
        </div>
        <div
          class="stat-card bg-green-50 border border-green-200 rounded-lg p-4"
        >
          <div class="text-2xl font-bold text-green-700">
            {{ sortedTextHistory.length }}
          </div>
          <div class="text-sm text-green-600">文案记录</div>
        </div>
        <div
          class="stat-card bg-purple-50 border border-purple-200 rounded-lg p-4"
        >
          <div class="text-2xl font-bold text-purple-700">
            {{ sortedImageHistory.length }}
          </div>
          <div class="text-sm text-purple-600">图片记录</div>
        </div>
      </div>
    </div>

    <!-- 标签页 -->
    <Tabs v-model="activeTab" class="w-full">
      <TabsList class="grid w-full grid-cols-2">
        <TabsTrigger value="text">文案历史</TabsTrigger>
        <TabsTrigger value="image">图片历史</TabsTrigger>
      </TabsList>

      <!-- 文案历史 -->
      <TabsContent value="text" class="mt-4">
        <div v-if="isLoading" class="loading-state">
          <div class="flex items-center justify-center py-8">
            <svg
              class="w-8 h-8 animate-spin text-primary"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
              />
            </svg>
            <span class="ml-2">加载中...</span>
          </div>
        </div>

        <div v-else-if="sortedTextHistory.length === 0" class="empty-state">
          <div class="text-center py-8 text-gray-500">
            <svg
              class="w-12 h-12 mx-auto mb-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="1"
                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
            <div class="text-lg font-medium">暂无文案历史记录</div>
            <div class="text-sm">开始生成文案后，这里会显示您的历史记录</div>
          </div>
        </div>

        <div v-else class="text-history">
          <div class="space-y-4">
            <div
              v-for="item in sortedTextHistory"
              :key="item.id"
              class="text-card bg-white border rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow"
            >
              <div class="flex items-start justify-between mb-2">
                <div class="flex items-center gap-2">
                  <span
                    class="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full"
                  >
                    文案
                  </span>
                  <span class="text-xs text-gray-500">
                    {{ LogService.formatTime(item.createTime) }}
                  </span>
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  @click="copyText(item.content)"
                >
                  <svg
                    class="w-4 h-4"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
                    />
                  </svg>
                </Button>
              </div>
              <div class="text-sm text-gray-800 leading-relaxed">
                {{ item.content }}
              </div>
            </div>
          </div>
        </div>
      </TabsContent>

      <!-- 图片历史 -->
      <TabsContent value="image" class="mt-4">
        <div v-if="isLoading" class="loading-state">
          <div class="flex items-center justify-center py-8">
            <svg
              class="w-8 h-8 animate-spin text-primary"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
              />
            </svg>
            <span class="ml-2">加载中...</span>
          </div>
        </div>

        <div v-else-if="sortedImageHistory.length === 0" class="empty-state">
          <div class="text-center py-8 text-gray-500">
            <svg
              class="w-12 h-12 mx-auto mb-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="1"
                d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
              />
            </svg>
            <div class="text-lg font-medium">暂无图片历史记录</div>
            <div class="text-sm">开始生成图片后，这里会显示您的历史记录</div>
          </div>
        </div>

        <div v-else class="image-history">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div
              v-for="item in sortedImageHistory"
              :key="item.id"
              class="image-card bg-white border rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow"
            >
              <div class="aspect-square bg-gray-100">
                <img
                  :src="item.imageUrl"
                  :alt="item.prompt"
                  class="w-full h-full object-cover"
                  @error="handleImageError"
                />
              </div>
              <div class="p-4">
                <div class="flex items-center justify-between mb-2">
                  <div class="flex items-center gap-2">
                    <span
                      class="text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded-full"
                    >
                      图片
                    </span>
                    <span class="text-xs text-gray-500">
                      {{ LogService.formatTime(item.createTime) }}
                    </span>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    @click="downloadImage(item.imageUrl)"
                  >
                    <svg
                      class="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                      />
                    </svg>
                  </Button>
                </div>
                <div class="text-sm text-gray-800 line-clamp-2">
                  {{ item.prompt }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </TabsContent>
    </Tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useLog } from "@/composables/useLog";
import { LogService } from "@/api/log";
import { toast } from "vue-sonner";

// Props
interface Props {
  userId: number;
}

const props = defineProps<Props>();

// 使用日志组合式函数
const {
  textHistory,
  imageHistory,
  isLoading,
  error,
  searchKeyword,
  sortedTextHistory,
  sortedImageHistory,
  totalRecords,
  loadHistory,
  setSearchKeyword,
  clearSearch,
  clearError,
} = useLog();

// 本地状态
const activeTab = ref("text");

// 方法
const handleSearch = (event: Event) => {
  const target = event.target as HTMLInputElement;
  setSearchKeyword(target.value);
};

const refreshHistory = async () => {
  await loadHistory(props.userId);
};

const copyText = async (text: string) => {
  // 优先使用现代 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    try {
      await navigator.clipboard.writeText(text);
      toast.success("文案已复制到剪贴板");
    } catch (err) {
      console.warn("Clipboard API 失败，使用降级方案:", err);
      fallbackCopyToClipboard(text);
    }
  } else {
    // 降级方案：使用传统的 document.execCommand
    fallbackCopyToClipboard(text);
  }
};

// 降级复制方案
function fallbackCopyToClipboard(text: string) {
  try {
    // 创建临时文本区域
    const textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.position = "fixed";
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);

    // 选择文本并复制
    textArea.focus();
    textArea.select();
    const successful = document.execCommand("copy");

    // 清理临时元素
    document.body.removeChild(textArea);

    if (successful) {
      toast.success("文案已复制到剪贴板");
    } else {
      toast.error("复制失败");
    }
  } catch (err) {
    console.error("复制失败:", err);
    toast.error("复制失败");
  }
}

const downloadImage = (imageUrl: string) => {
  const link = document.createElement("a");
  link.href = imageUrl;
  link.download = `image_${Date.now()}.jpg`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  toast.success("图片下载已开始");
};

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  img.src = "/placeholder-image.jpg"; // 设置占位图片
};

// 生命周期
onMounted(() => {
  loadHistory(props.userId);
});
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
